from file_manage import models
from Method_Decorate import Get_django_log
import subprocess
import os
import re
from Method_Decorate.Inside_action import send_emial_app_error
from Automated_Testing import settings
# import queue
import time

#异常类：
class MyException(BaseException):
    def __init__(self,message):
        self.message = message


class compile_app():

    log_action = Get_django_log.log_action()
    # def __init__(self):
    #     # self.log_action=Get_django_log.log_action()
    #     self.queue=queue.Queue(maxsize=500)



    @staticmethod
    def compile_log(pk):
        """
        编译记录的位置
        :param pk:
        :return:
        """
        app_database = models.App.objects.get(pk=pk)
        compile_process_log_path = os.path.join(settings.log_path, "compile_path")
        if not os.path.exists(compile_process_log_path):
            os.mkdir(compile_process_log_path)
        return os.path.join(compile_process_log_path, "{0}_{1}.txt".format(app_database.name, pk))
    @staticmethod
    def compile_action(pk,arg=None):
        """
        编译app
        :param pk:app主键
        :return:
        """

        app_database=models.App.objects.get(pk=pk)
        run_command=app_database.get_shell_compile_command()
        folder_path=app_database.app_script.get_script_path_exclude_file()
#########记录compile信息 用于显示
        # compile_process_log_path=os.path.join(settings.log_path,"compile_path")
        # if not os.path.exists(compile_process_log_path):
        #     os.mkdir(compile_process_log_path)
        # compile_process_log=os.path.join(compile_process_log_path,"{0}_{1}.txt".format(app_database.name,pk))
        compile_process_log=compile_app.compile_log(pk)
#########################
        if app_database.judge_condition_run():    #如果没有在跑样本是可以直接编译
            raise Exception("此时正被占用不可选择！！")
        # compile_app.log_action.tool_debug("开始编译操作！")
        Get_django_log.log_action.log_django.info("开始编译操作！app_name:{0}".format(app_database.name))
        #新进程
        app_database.set_condition_compile()
        process_f = subprocess.Popen(run_command, shell=True, stdout=subprocess.PIPE,
                              stdin=subprocess.PIPE, stderr=subprocess.PIPE,
                              cwd=folder_path)#,universal_newlines=True)
        error_flag=False
        with open(compile_process_log,"w") as f:
            while True:
                # time.sleep(0.01)
                try:
                    process_f.stdout.flush()
                    line=process_f.stdout.readline().decode("UTF-8")
                    print(line)
                    f.write(line)
                    f.flush()
                    # if not line:
                    #     break
                    if "sername" in line:
                        Get_django_log.log_action.log_django.warning("需要输入用户名!app_name:{0}".format(app_database.name))
                        return "需要输入用户名!app_name:{0}".format(app_database.name)
                    if "everything is ok" in line:
                        break
                    # 12.25
                    # if  re.search(r'^#+error log#+$',line,re.M|re.I)!=None:
                    #     error_flag=True
                    #     break
                    if process_f.poll()!=None:
                        break
                except Exception as e:
                    print(e)
                    # f.write(e)
                    # f.flush()
                    continue
            # if(error_flag==True and arg!=None):
            #     send_emial_app_error(arg,compile_process_log)

            app_database.set_compile_time()
            Get_django_log.log_action.log_django.info("结束编译操作！app_name:{0}".format(app_database.name))
            app_database.set_condition_free()
            return "编译操作完成！app_name:{0}".format(app_database.name)

    @staticmethod
    def inquery_compile_log(pk):
        """
        查询编译状态
        :param pk:
        :return:
        """
        # app_database = models.App.objects.get(pk=pk)
        compile_process_log = compile_app.compile_log(pk)
        if not os.path.isfile(compile_process_log):#如果没有文件则创建
            file=open(compile_process_log,"w")
            file.close()
        with open(compile_process_log,"r") as f:
            # tmp=f.read()
            list_read=f.readlines()
            list_read=list_read[-50:]
        return list_read
